package com.blessx.dragracing;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private WebView webView;

    private ProgressDialog progressDialog;

    private boolean isBoole = true, IfFirstOpen;

    private Uri uri;

    private final int VIDEO_CODE = 14;
    private final int PHOTO_CODE = 12;

    private ValueCallback<Uri[]> valueCallbackPhoto;

    private ValueCallback<Uri> valueCallbackVideo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webView);

        MuVegas();

        webView = new WebView(this);
        webView.setWebViewClient(new myWebViewClient());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webView.setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_IMPORTANT, true);
        }
        WebSettings webSettings = webView.getSettings();

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        setWebView(webSettings);

        webView.loadUrl("file:///android_asset/index.html");
        setContentView(webView);
    }

    public void setWebView(WebSettings settings) {
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setSupportMultipleWindows(false);
        settings.setDisplayZoomControls(false);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == VIDEO_CODE) {
            if (null != valueCallbackVideo) {
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                valueCallbackVideo.onReceiveValue(result);
                valueCallbackVideo = null;
            } else if (null != valueCallbackPhoto) {
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (result != null) {
                    valueCallbackPhoto.onReceiveValue(new Uri[]{result});
                } else {
                    valueCallbackPhoto.onReceiveValue(null);
                }
                valueCallbackPhoto = null;
            }
        } else if (requestCode == PHOTO_CODE) {

            if (valueCallbackVideo != null) {

            } else if (valueCallbackPhoto != null) {
                FFVegas(resultCode, data);
            }
        }
    }

    public void MuVegas() {
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void opVegas(String accept) {
        if (accept.contains("video")) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            //开启摄像机
            startActivityForResult(intent, VIDEO_CODE);
        } else {

            String filePath = Environment.getExternalStorageDirectory() + File.separator
                    + Environment.DIRECTORY_PICTURES + File.separator;
            String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.ENGLISH)) + ".jpg";
            uri = Uri.fromFile(new File(filePath + fileName));


            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "Image Chooser"), PHOTO_CODE);

        }
    }

    private void FFVegas(int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            GBVegas();
            if (data != null) {

                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
                    results = new Uri[]{uriData};
                    for (Uri uri : results) {
                    }
                    valueCallbackPhoto.onReceiveValue(results);
                } else {
                    valueCallbackPhoto.onReceiveValue(null);
                }
            } else {
                valueCallbackPhoto.onReceiveValue(new Uri[]{uri});
            }
        } else {
            valueCallbackPhoto.onReceiveValue(null);
        }
        valueCallbackPhoto = null;
    }

    private void GBVegas() {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(uri);
        sendBroadcast(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
            webView.destroy();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    class myWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = String.valueOf(request.getUrl());

            if (url.contains("about:blank")) {
                view.goBack();
            }
            return super.shouldOverrideUrlLoading(view, request);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("ftp")) {
                view.loadUrl(url);
                return true;
            } else if (url.startsWith("scheme://")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }


    }
}

